import 'dart:async';
import 'dart:collection';

import 'package:flutter/services.dart';
import 'package:flutter_yfree/YFree.dart';
import 'package:universal_html/js.dart';

final myPlugin = MyPlugin();

class MyPlugin {
  final _myPlugin = MethodChannel('MyPlugin');

  void _invokeMethod_async(method, {Map<String, dynamic>? arguments, onResult(dynamic result)?}) {
    if (yIsWeb) {
      yFreeWebPlugin!.invokeMethod(method, args: [JsObject.jsify(arguments ?? {}), (dynamic result) => onResult?.call(result)]);
    } else {
      _myPlugin.invokeMethod(method, arguments).then((result) {
        onResult?.call((result is Map) ? Map.from(result) : result);
      });
    }
  }

  dynamic _invokeMethod_sync<T>(method, {Map<String, dynamic>? arguments}) async {
    if (yIsWeb) {
      return await yRunCompleter((completer) {
        yFreeWebPlugin!.invokeMethod(method, args: [JsObject.jsify(arguments ?? {}), (dynamic result) => completer.complete(result)]);
      });
    } else {
      final result = await _myPlugin.invokeMethod(method, arguments);
      return (result is Map) ? Map.from(result) : result;
    }
  }

  Future<String?> getMsg() async => await _invokeMethod_sync("getMsg");

  void goH5() => _invokeMethod_sync("goH5");

  void goUniapp(String checkVersionJkid) => _invokeMethod_sync("goUniapp", arguments: LinkedHashMap()..["checkVersionJkid"] = checkVersionJkid);
}
